import { useState, useMemo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Card, Table, Input, Button, Space } from 'antd';
import { ArrowLeftOutlined, SearchOutlined } from '@ant-design/icons';
import { getCourseStudents, CourseStudent } from '../../api/teacher';
import { Course } from '../../types';
import { mockCourses } from '../../api/mockData';

export default function CourseStudents() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const courseId = searchParams.get('id') || '';
  const [searchText, setSearchText] = useState('');

  // 获取课程信息
  const course: Course | undefined = mockCourses.find(c => c.id === courseId);

  // 获取课程学生列表
  const { data: students = [], isLoading } = useQuery({
    queryKey: ['courseStudents', courseId],
    queryFn: () => getCourseStudents(courseId),
    enabled: !!courseId,
  });

  // 过滤学生列表
  const filteredStudents = useMemo(() => {
    if (!searchText.trim()) {
      return students;
    }
    const lowerSearch = searchText.toLowerCase();
    return students.filter(student => 
      student.name.toLowerCase().includes(lowerSearch) ||
      student.studentNo.toLowerCase().includes(lowerSearch) ||
      student.college.toLowerCase().includes(lowerSearch) ||
      student.major.toLowerCase().includes(lowerSearch) ||
      student.clazz.toLowerCase().includes(lowerSearch)
    );
  }, [students, searchText]);

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
    },
    {
      title: '学号',
      dataIndex: 'studentNo',
      key: 'studentNo',
      width: 120,
    },
    {
      title: '班级',
      dataIndex: 'clazz',
      key: 'clazz',
      width: 120,
    },
    {
      title: '专业',
      dataIndex: 'major',
      key: 'major',
      width: 180,
    },
  ];

  return (
    <div className="p-4 pb-24">
      {/* 返回按钮和标题 */}
      <div className="flex items-center gap-2 mb-4">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/teacher')}
          className="flex items-center"
        >
          返回
        </Button>
      </div>

      <Card>
        <div className="mb-4">
          <div className="text-lg font-semibold mb-1">课程：{course?.name || '未找到课程'}</div>
          <div className="text-sm text-slate-500 mb-4">
            {course?.timeSlots?.[0] && (
              <>
                上课时间：{course.timeSlots[0].start}-{course.timeSlots[0].end}
                {course.timeSlots[0].room && ` | 教室：${course.timeSlots[0].room}`}
              </>
            )}
            {' | '}学分：{course?.credit || '-'} | 选课人数：{students.length}/{course?.capacity || 0}
          </div>
          
          {/* 搜索框 */}
          <Space className="w-full mb-4">
            <Input
              placeholder="搜索学生（姓名、学号、班级、专业）"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
              style={{ maxWidth: 400 }}
            />
            {searchText && (
              <span className="text-sm text-slate-500">
                共找到 {filteredStudents.length} 条结果
              </span>
            )}
          </Space>
        </div>

        <Table
          dataSource={filteredStudents}
          columns={columns}
          rowKey="id"
          loading={isLoading}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          locale={{
            emptyText: '暂无学生',
          }}
        />
      </Card>
    </div>
  );
}

